package org.example.customer.rest;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author jie.luo
 * @description
 * @since 2020-06-16
 */
@RestController
public class CustomerRest {

    @GetMapping("/hello")
    public String helloCustomer() {
        return "hello customer";
    }


    @HystrixCommand(fallbackMethod = "fallbackMethodTest", commandProperties = {
            @HystrixProperty(value = "hystrix.command.circuitBreaker.enabled", name = "true"),
            @HystrixProperty(value = "hystrix.command.circuitBreaker.requestVolumeThreshold", name = "20"),
            @HystrixProperty(value = "hystrix.command.circuitBreaker.sleepWindowInMilliseconds", name = "5000"),
            @HystrixProperty(value = "hystrix.command.circuitBreaker.errorThresholdPercentage", name = "50")
    })
    @GetMapping("/test-hystrix")
    public String testHystrix() {
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject("http://localhost:8001/provider/user?userId=1", String.class);
        System.out.println(forObject);
        return forObject;
    }

    @HystrixCommand(fallbackMethod = "fallbackMethodTest1")
    @GetMapping("/test-hystrix1")
    public String testHystrix1(Boolean flag) {
        if (flag) {
            throw new RuntimeException("");
        }
        return "测试服务降级";
    }

    private String fallbackMethodTest1(Boolean flag) {
        return "服务太拥挤了，请稍后再试....";
    }

    private String fallbackMethodTest() {
        return "服务太拥挤了，请稍后再试....";
    }
}
